package cn.guetzjb.core.utils;

import cn.guetzjb.core.constant.SecurityConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@UtilityClass
@Slf4j
public class JwtUtils {

    public static String secret = "woaizhangjinbo";

    public String createToken(Map<String, Object> claim) {
        return Jwts.builder().setClaims(claim).signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    public Claims parseToken(String token) {
        if (token.startsWith("Bearer ")) {
            token = token.replace("Bearer ", "");
        }
        try {
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            log.error("解析令牌出错:{}", e.getMessage());
        }
        return null;
    }

    public Long getUserId(String token) {
        Claims claims = parseToken(token);
        return claims.get(SecurityConstants.DETAILS_USER_ID, Long.class);
    }

    public String getUsername(String token) {
        Claims claims = parseToken(token);
        return claims.get(SecurityConstants.DETAILS_USERNAME, String.class);
    }

    public String getUserKey(String token) {
        Claims claims = parseToken(token);
        return claims.get(SecurityConstants.USER_KEY, String.class);
    }

}
